home *** CD-ROM | disk | FTP | other *** search
/ PC World 2007 September / PCWorld_2007-09_cd.bin / komunikace / firefox / Firefox Setup 2.0.0.6.exe / nonlocalized / components / FeedProcessor.js < prev    next >
Encoding:
JavaScript  |  2007-07-25  |  59.8 KB  |  1,826 lines

  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public License Version
  6.  * 1.1 (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is mozilla.org code.
  16.  *
  17.  * The Initial Developer of the Original Code is Robert Sayre.
  18.  * Portions created by the Initial Developer are Copyright (C) 2006
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *   Ben Goodger <beng@google.com>
  23.  *   Myk Melez <myk@mozilla.org>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. function LOG(str) {
  40.   dump("*** " + str + "\n");
  41. }
  42.  
  43. const Ci = Components.interfaces;
  44. const Cc = Components.classes;
  45. const Cr = Components.results;
  46.  
  47. const IO_CONTRACTID = "@mozilla.org/network/io-service;1"
  48. const BAG_CONTRACTID = "@mozilla.org/hash-property-bag;1"
  49. const ARRAY_CONTRACTID = "@mozilla.org/array;1";
  50. const SAX_CONTRACTID = "@mozilla.org/saxparser/xmlreader;1";
  51. const UNESCAPE_CONTRACTID = "@mozilla.org/feed-unescapehtml;1";
  52.  
  53. var gIoService = Cc[IO_CONTRACTID].getService(Ci.nsIIOService);
  54. var gUnescapeHTML = Cc[UNESCAPE_CONTRACTID].
  55.                     getService(Ci.nsIScriptableUnescapeHTML);
  56.  
  57. const XMLNS = "http://www.w3.org/XML/1998/namespace";
  58. const RSS090NS = "http://my.netscape.com/rdf/simple/0.9/";
  59.  
  60. /***** Some general utils *****/
  61. function strToURI(link, base) {
  62.   var base = base || null;
  63.   try {
  64.     return gIoService.newURI(link, null, base);
  65.   }
  66.   catch(e) {
  67.     return null;
  68.   }
  69. }
  70.  
  71. function isArray(a) {
  72.   return isObject(a) && a.constructor == Array;
  73. }
  74.  
  75. function isObject(a) {
  76.   return (a && typeof a == "object") || isFunction(a);
  77. }
  78.  
  79. function isFunction(a) {
  80.   return typeof a == "function";
  81. }
  82.  
  83. function isIID(a, iid) {
  84.   var rv = false;
  85.   try {
  86.     a.QueryInterface(iid);
  87.     rv = true;
  88.   }
  89.   catch(e) {
  90.   }
  91.   return rv;
  92. }
  93.  
  94. function isIArray(a) {
  95.   return isIID(a, Ci.nsIArray);
  96. }
  97.  
  98. function isIFeedContainer(a) {
  99.   return isIID(a, Ci.nsIFeedContainer);
  100. }
  101.  
  102. function stripTags(someHTML) {
  103.   return someHTML.replace(/<[^>]+>/g,"");
  104. }
  105.  
  106. /**
  107.  * Searches through an array of links and returns a JS array 
  108.  * of matching property bags.
  109.  */
  110. const IANA_URI = "http://www.iana.org/assignments/relation/";
  111. function findAtomLinks(rel, links) {
  112.   var rvLinks = [];
  113.   for (var i = 0; i < links.length; ++i) {
  114.     var linkElement = links.queryElementAt(i, Ci.nsIPropertyBag2);
  115.     // atom:link MUST have @href
  116.     if (bagHasKey(linkElement, "href")) {
  117.       var relAttribute = null;
  118.       if (bagHasKey(linkElement, "rel"))
  119.         relAttribute = linkElement.getPropertyAsAString("rel")
  120.       if ((!relAttribute && rel == "alternate") || relAttribute == rel) {
  121.         rvLinks.push(linkElement);
  122.         continue;
  123.       }
  124.       // catch relations specified by IANA URI 
  125.       if (relAttribute == IANA_URI + rel) {
  126.         rvLinks.push(linkElement);
  127.       }
  128.     }
  129.   }
  130.   return rvLinks;
  131. }
  132.  
  133. function xmlEscape(s) {
  134.   s = s.replace(/&/g, "&");
  135.   s = s.replace(/>/g, ">");
  136.   s = s.replace(/</g, "<");
  137.   s = s.replace(/"/g, """);
  138.   s = s.replace(/'/g, "'");
  139.   return s;
  140. }
  141.  
  142. function arrayContains(array, element) {
  143.   for (var i = 0; i < array.length; ++i) {
  144.     if (array[i] == element) {
  145.       return true;
  146.     }
  147.   }
  148.   return false;
  149. }
  150.  
  151. // XXX add hasKey to nsIPropertyBag
  152. function bagHasKey(bag, key) {
  153.   try {
  154.     bag.getProperty(key);
  155.     return true;
  156.   }
  157.   catch (e) {
  158.     return false;
  159.   }
  160. }
  161.  
  162. function makePropGetter(key) {
  163.   return function FeedPropGetter(bag) {
  164.     try {
  165.       return value = bag.getProperty(key);
  166.     }
  167.     catch(e) {
  168.     }
  169.     return null;
  170.   }
  171. }
  172.  
  173.  
  174.  
  175. /**
  176.  * XXX Thunderbird's W3C-DTF function
  177.  *
  178.  * Converts a W3C-DTF (subset of ISO 8601) date string to an IETF date
  179.  * string.  W3C-DTF is described in this note:
  180.  * http://www.w3.org/TR/NOTE-datetime IETF is obtained via the Date
  181.  * object's toUTCString() method.  The object's toString() method is
  182.  * insufficient because it spells out timezones on Win32
  183.  * (f.e. "Pacific Standard Time" instead of "PST"), which Mail doesn't
  184.  * grok.  For info, see
  185.  * http://lxr.mozilla.org/mozilla/source/js/src/jsdate.c#1526.
  186.  */
  187. const HOURS_TO_MINUTES = 60;
  188. const MINUTES_TO_SECONDS = 60;
  189. const SECONDS_TO_MILLISECONDS = 1000;
  190. const MINUTES_TO_MILLISECONDS = MINUTES_TO_SECONDS * SECONDS_TO_MILLISECONDS;
  191. const HOURS_TO_MILLISECONDS = HOURS_TO_MINUTES * MINUTES_TO_MILLISECONDS;
  192. function W3CToIETFDate(dateString) {
  193.  
  194.   var parts = dateString.match(/(\d\d\d\d)(-(\d\d))?(-(\d\d))?(T(\d\d):(\d\d)(:(\d\d)(\.(\d+))?)?(Z|([+-])(\d\d):(\d\d))?)?/);
  195.  
  196.   // Here's an example of a W3C-DTF date string and what .match returns for it.
  197.   // 
  198.   // date: 2003-05-30T11:18:50.345-08:00
  199.   // date.match returns array values:
  200.   //
  201.   //   0: 2003-05-30T11:18:50-08:00,
  202.   //   1: 2003,
  203.   //   2: -05,
  204.   //   3: 05,
  205.   //   4: -30,
  206.   //   5: 30,
  207.   //   6: T11:18:50-08:00,
  208.   //   7: 11,
  209.   //   8: 18,
  210.   //   9: :50,
  211.   //   10: 50,
  212.   //   11: .345,
  213.   //   12: 345,
  214.   //   13: -08:00,
  215.   //   14: -,
  216.   //   15: 08,
  217.   //   16: 00
  218.  
  219.   // Create a Date object from the date parts.  Note that the Date
  220.   // object apparently can't deal with empty string parameters in lieu
  221.   // of numbers, so optional values (like hours, minutes, seconds, and
  222.   // milliseconds) must be forced to be numbers.
  223.   var date = new Date(parts[1], parts[3] - 1, parts[5], parts[7] || 0,
  224.                       parts[8] || 0, parts[10] || 0, parts[12] || 0);
  225.  
  226.   // We now have a value that the Date object thinks is in the local
  227.   // timezone but which actually represents the date/time in the
  228.   // remote timezone (f.e. the value was "10:00 EST", and we have
  229.   // converted it to "10:00 PST" instead of "07:00 PST").  We need to
  230.   // correct that.  To do so, we're going to add the offset between
  231.   // the remote timezone and UTC (to convert the value to UTC), then
  232.   // add the offset between UTC and the local timezone //(to convert
  233.   // the value to the local timezone).
  234.  
  235.   // Ironically, W3C-DTF gives us the offset between UTC and the
  236.   // remote timezone rather than the other way around, while the
  237.   // getTimezoneOffset() method of a Date object gives us the offset
  238.   // between the local timezone and UTC rather than the other way
  239.   // around.  Both of these are the additive inverse (i.e. -x for x)
  240.   // of what we want, so we have to invert them to use them by
  241.   // multipying by -1 (f.e. if "the offset between UTC and the remote
  242.   // timezone" is -5 hours, then "the offset between the remote
  243.   // timezone and UTC" is -5*-1 = 5 hours).
  244.  
  245.   // Note that if the timezone portion of the date/time string is
  246.   // absent (which violates W3C-DTF, although ISO 8601 allows it), we
  247.   // assume the value to be in UTC.
  248.  
  249.   // The offset between the remote timezone and UTC in milliseconds.
  250.   var remoteToUTCOffset = 0;
  251.   if (parts[13] && parts[13] != "Z") {
  252.     var direction = (parts[14] == "+" ? 1 : -1);
  253.     if (parts[15])
  254.       remoteToUTCOffset += direction * parts[15] * HOURS_TO_MILLISECONDS;
  255.     if (parts[16])
  256.       remoteToUTCOffset += direction * parts[16] * MINUTES_TO_MILLISECONDS;
  257.   }
  258.   remoteToUTCOffset = remoteToUTCOffset * -1; // invert it
  259.  
  260.   // The offset between UTC and the local timezone in milliseconds.
  261.   var UTCToLocalOffset = date.getTimezoneOffset() * MINUTES_TO_MILLISECONDS;
  262.   UTCToLocalOffset = UTCToLocalOffset * -1; // invert it
  263.   date.setTime(date.getTime() + remoteToUTCOffset + UTCToLocalOffset);
  264.  
  265.   return date.toUTCString();
  266. }
  267.  
  268. const RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  269. // namespace map
  270. var gNamespaces = {
  271.   "http://webns.net/mvcb/":"admin",
  272.   "http://backend.userland.com/rss":"",
  273.   "http://blogs.law.harvard.edu/tech/rss":"",
  274.   "http://www.w3.org/2005/Atom":"atom",
  275.   "http://purl.org/atom/ns#":"atom03",
  276.   "http://purl.org/rss/1.0/modules/content/":"content",
  277.   "http://purl.org/dc/elements/1.1/":"dc",
  278.   "http://purl.org/dc/terms/":"dcterms",
  279.   "http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf",
  280.   "http://purl.org/rss/1.0/":"rss1",
  281.   "http://my.netscape.com/rdf/simple/0.9/":"rss1",
  282.   "http://wellformedweb.org/CommentAPI/":"wfw",                              
  283.   "http://purl.org/rss/1.0/modules/wiki/":"wiki", 
  284.   "http://www.w3.org/XML/1998/namespace":"xml"
  285. }
  286.  
  287.  
  288. function FeedResult() {}
  289. FeedResult.prototype = {
  290.   bozo: false,
  291.   doc: null,
  292.   version: null,
  293.   headers: null,
  294.   uri: null,
  295.   stylesheet: null,
  296.  
  297.   registerExtensionPrefix: function FR_registerExtensionPrefix(ns, prefix) {
  298.     throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  299.   },
  300.  
  301.   QueryInterface: function FR_QI(iid) {
  302.     if (iid.equals(Ci.nsIFeedResult) ||
  303.         iid.equals(Ci.nsISupports))
  304.       return this;
  305.  
  306.     throw Cr.NS_ERROR_NOINTERFACE;
  307.   },
  308. }  
  309.  
  310. function Feed() {
  311.   this.subtitle = null;
  312.   this.title = null;
  313.   this.items = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  314.   this.link = null;
  315.   this.id = null;
  316.   this.generator = null;
  317.   this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  318.   this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  319.   this.baseURI = null;
  320. }
  321.  
  322. Feed.prototype = {
  323.   searchLists: {
  324.     subtitle: ["description","dc:description","rss1:description",
  325.                "atom03:tagline","atom:subtitle"],
  326.     items: ["items","atom03_entries","entries"],
  327.     id: ["atom:id","rdf:about"],
  328.     generator: ["generator"],
  329.     authors : ["authors"],
  330.     contributors: ["contributors"],
  331.     title: ["title","rss1:title", "atom03:title","atom:title"],
  332.     link:  [["link",strToURI],["rss1:link",strToURI]],
  333.     categories: ["categories", "dc:subject"],
  334.     rights: ["atom03:rights","atom:rights"],
  335.     cloud: ["cloud"],
  336.     image: ["image", "rss1:image", "atom:logo"],
  337.     textInput: ["textInput", "rss1:textinput"],
  338.     skipDays: ["skipDays"],
  339.     skipHours: ["skipHours"],
  340.     updated: ["pubDate", "lastBuildDate", "atom03:modified", "dc:date",
  341.               "dcterms:modified", "atom:updated"]
  342.   },
  343.  
  344.   normalize: function Feed_normalize() {
  345.     fieldsToObj(this, this.searchLists);
  346.     if (this.skipDays)
  347.       this.skipDays = this.skipDays.getProperty("days");
  348.     if (this.skipHours)
  349.       this.skipHours = this.skipHours.getProperty("hours");
  350.  
  351.     if (this.updated)
  352.       this.updated = dateParse(this.updated);
  353.  
  354.     // Assign Atom link if needed
  355.     if (bagHasKey(this.fields, "links"))
  356.       this._atomLinksToURI();
  357.  
  358.     // Resolve relative image links
  359.     if (this.image && bagHasKey(this.image, "url")) {
  360.       this._resolveImageLink();
  361.     }
  362.  
  363.     this._resetBagMembersToRawText([this.searchLists.subtitle, 
  364.                                     this.searchLists.title]);
  365.   },
  366.  
  367.   _atomLinksToURI: function Feed_linkToURI() {
  368.     var links = this.fields.getPropertyAsInterface("links", Ci.nsIArray);
  369.     var alternates = findAtomLinks("alternate", links);
  370.     if (alternates.length > 0) {
  371.       var href = alternates[0].getPropertyAsAString("href");
  372.       var base;
  373.       if (bagHasKey(alternates[0], "xml:base"))
  374.         base = alternates[0].getPropertyAsAString("xml:base");
  375.       this.link = this._resolveURI(href, base);
  376.     }
  377.   },
  378.  
  379.   _resolveImageLink: function Feed_resolveImageLink() {
  380.     var base;
  381.     if (bagHasKey(this.image, "xml:base"))
  382.       base = this.image.getPropertyAsAString("xml:base");
  383.     var url = this._resolveURI(this.image.getPropertyAsAString("url"), base);
  384.     if (url)
  385.       this.image.setPropertyAsAString("url", url.spec);
  386.   },
  387.  
  388.   _resolveURI: function Feed_resolveURI(linkSpec, baseSpec) {
  389.     var uri = null;
  390.     try {
  391.       var base = baseSpec ? strToURI(baseSpec, this.baseURI) : this.baseURI;
  392.       uri = strToURI(linkSpec, base);
  393.     }
  394.     catch(e) {
  395.       LOG(e);
  396.     }
  397.  
  398.     return uri;
  399.   },
  400.  
  401.   // reset the bag to raw contents, not text constructs
  402.   _resetBagMembersToRawText: function Feed_resetBagMembers(fieldLists) {
  403.     for (var i=0; i<fieldLists.length; i++) {      
  404.       for (var j=0; j<fieldLists[i].length; j++) {
  405.         if (bagHasKey(this.fields, fieldLists[i][j])) {
  406.           var textConstruct = this.fields.getProperty(fieldLists[i][j]);
  407.           this.fields.setPropertyAsAString(fieldLists[i][j],
  408.                                            textConstruct.text);
  409.         }
  410.       }
  411.     }
  412.   },
  413.    
  414.   QueryInterface: function Feed_QI(iid) {
  415.     if (iid.equals(Ci.nsIFeed) ||
  416.         iid.equals(Ci.nsIFeedContainer) ||
  417.         iid.equals(Ci.nsISupports))
  418.     return this;
  419.     throw Cr.NS_ERROR_NOINTERFACE;
  420.   }
  421. }
  422.  
  423. function Entry() {
  424.   this.summary = null;
  425.   this.content = null;
  426.   this.title = null;
  427.   this.fields = Cc["@mozilla.org/hash-property-bag;1"].
  428.     createInstance(Ci.nsIWritablePropertyBag2);
  429.   this.link = null;
  430.   this.id = null;
  431.   this.baseURI = null;
  432.   this.updated = null;
  433.   this.published = null;
  434.   this.authors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  435.   this.contributors = Cc[ARRAY_CONTRACTID].createInstance(Ci.nsIMutableArray);
  436. }
  437.   
  438. Entry.prototype = {
  439.   fields: null,
  440.   enclosures: null,
  441.   mediaContent: null,
  442.   
  443.   searchLists: {
  444.     title: ["title", "rss1:title", "atom03:title", "atom:title"],
  445.     link: [["link",strToURI],["rss1:link",strToURI]],
  446.     id: [["guid", makePropGetter("guid")], "rdf:about",
  447.          "atom03:id", "atom:id"],
  448.     authors : ["authors"],
  449.     contributors: ["contributors"],
  450.     summary: ["description", "rss1:description", "dc:description",
  451.               "atom03:summary", "atom:summary"],
  452.     content: ["content:encoded","atom03:content","atom:content"],
  453.     rights: ["atom03:rights","atom:rights"],
  454.     published: ["atom03:issued", "dcterms:issued", "atom:published"],
  455.     updated: ["pubDate", "atom03:modified", "dc:date", "dcterms:modified",
  456.               "atom:updated"]
  457.   },
  458.   
  459.   normalize: function Entry_normalize() {
  460.     fieldsToObj(this, this.searchLists);
  461.  
  462.     // Assign Atom link if needed
  463.     if (bagHasKey(this.fields, "links"))
  464.       this._atomLinksToURI();
  465.  
  466.     // The link might be a guid w/ permalink=true
  467.     if (!this.link && bagHasKey(this.fields, "guid")) {
  468.       var guid = this.fields.getProperty("guid");
  469.       var isPermaLink = true;
  470.       
  471.       if (bagHasKey(guid, "isPermaLink"))
  472.         isPermaLink = guid.getProperty("isPermaLink").toLowerCase() != "false";
  473.       
  474.       if (guid && isPermaLink)
  475.         this.link = strToURI(guid.getProperty("guid"));
  476.     }
  477.  
  478.     if (this.updated)
  479.       this.updated = dateParse(this.updated);
  480.     if (this.published)
  481.       this.published = dateParse(this.published);
  482.  
  483.     this._resetBagMembersToRawText([this.searchLists.content, 
  484.                                     this.searchLists.summary, 
  485.                                     this.searchLists.title]);
  486.   },
  487.   
  488.   QueryInterface: function(iid) {
  489.     if (iid.equals(Ci.nsIFeedEntry) ||
  490.         iid.equals(Ci.nsIFeedContainer) ||
  491.         iid.equals(Ci.nsISupports))
  492.     return this;
  493.  
  494.     throw Cr.NS_ERROR_NOINTERFACE;
  495.   }
  496. }
  497.  
  498. Entry.prototype._atomLinksToURI = Feed.prototype._atomLinksToURI;
  499. Entry.prototype._resolveURI = Feed.prototype._resolveURI;
  500. Entry.prototype._resetBagMembersToRawText = 
  501.    Feed.prototype._resetBagMembersToRawText;
  502.  
  503. // TextConstruct represents and element that could contain (X)HTML
  504. function TextConstruct() {
  505.   this.lang = null;
  506.   this.base = null;
  507.   this.type = "text";
  508.   this.text = null;
  509. }
  510.  
  511. TextConstruct.prototype = {
  512.   plainText: function TC_plainText() {
  513.     if (this.type != "text") {
  514.       return gUnescapeHTML.unescape(stripTags(this.text));
  515.     }
  516.     return this.text;
  517.   },
  518.  
  519.   createDocumentFragment: function TC_createDocumentFragment(element) {
  520.     if (this.type == "text") {
  521.       var doc = element.ownerDocument;
  522.       var docFragment = doc.createDocumentFragment();
  523.       var node = doc.createTextNode(this.text);
  524.       docFragment.appendChild(node);
  525.       return docFragment;
  526.     }
  527.     var isXML;
  528.     if (this.type == "xhtml")
  529.       isXML = true
  530.     else if (this.type == "html")
  531.       isXML = false;
  532.     else
  533.       return null;
  534.  
  535.     return gUnescapeHTML.parseFragment(this.text, isXML, this.base, element);
  536.   },
  537.  
  538.   QueryInterface: function(iid) {
  539.     if (iid.equals(Ci.nsIFeedTextConstruct) ||
  540.         iid.equals(Ci.nsISupports))
  541.     return this;
  542.  
  543.     throw Cr.NS_ERROR_NOINTERFACE;
  544.   }
  545. }
  546.  
  547. // Generator represents the software that produced the feed
  548. function Generator() {
  549.   this.lang = null;
  550.   this.agent = null;
  551.   this.version = null;
  552.   this.uri = null;
  553.  
  554.   // nsIFeedElementBase
  555.   this._attributes = null;
  556.   this.baseURI = null;
  557. }
  558.  
  559. Generator.prototype = {
  560.  
  561.   get attributes() {
  562.     return this._attributes;
  563.   },
  564.  
  565.   set attributes(value) {
  566.     this._attributes = value;
  567.     this.version = this._attributes.getValueFromName("","version");
  568.     var uriAttribute = this._attributes.getValueFromName("","uri") ||
  569.                        this._attributes.getValueFromName("","url");
  570.     this.uri = strToURI(uriAttribute, this.baseURI);
  571.  
  572.     // RSS1
  573.     uriAttribute = this._attributes.getValueFromName(RDF_NS,"resource");
  574.     if (uriAttribute) {
  575.       this.agent = uriAttribute;
  576.       this.uri = strToURI(uriAttribute, this.baseURI);
  577.     }
  578.   },
  579.  
  580.   QueryInterface: function(iid) {
  581.     if (iid.equals(Ci.nsIFeedGenerator) ||
  582.         iid.equals(Ci.nsIFeedElementBase) ||
  583.         iid.equals(Ci.nsISupports))
  584.     return this;
  585.  
  586.     throw Cr.NS_ERROR_NOINTERFACE;
  587.   }
  588. }
  589.  
  590. function Person() {
  591.   this.name = null;
  592.   this.uri = null;
  593.   this.email = null;
  594.  
  595.   // nsIFeedElementBase
  596.   this.attributes = null;
  597.   this.baseURI = null;
  598. }
  599.  
  600. Person.prototype = {
  601.   QueryInterface: function(iid) {
  602.     if (iid.equals(Ci.nsIFeedPerson) ||
  603.         iid.equals(Ci.nsIFeedElementBase) ||
  604.         iid.equals(Ci.nsISupports))
  605.     return this;
  606.  
  607.     throw Cr.NS_ERROR_NOINTERFACE;
  608.   }
  609. }
  610.  
  611. /** 
  612.  * Map a list of fields into properties on a container.
  613.  *
  614.  * @param container An nsIFeedContainer
  615.  * @param fields A list of fields to search for. List members can
  616.  *               be a list, in which case the second member is 
  617.  *               transformation function (like parseInt).
  618.  */
  619. function fieldsToObj(container, fields) {
  620.   var props,prop,field,searchList;
  621.   for (var key in fields) {
  622.     searchList = fields[key];
  623.     for (var i=0; i < searchList.length; ++i) {
  624.       props = searchList[i];
  625.       prop = null;
  626.       field = isArray(props) ? props[0] : props;
  627.       try {
  628.         prop = container.fields.getProperty(field);
  629.       } 
  630.       catch(e) { 
  631.       }
  632.       if (prop) {
  633.         prop = isArray(props) ? props[1](prop) : prop;
  634.         container[key] = prop;
  635.       }
  636.     }
  637.   }
  638. }
  639.  
  640. /**
  641.  * Lower cases an element's localName property
  642.  * @param   element A DOM element.
  643.  *
  644.  * @returns The lower case localName property of the specified element
  645.  */
  646. function LC(element) {
  647.   return element.localName.toLowerCase();
  648. }
  649.  
  650. // TODO move these post-processor functions
  651. // create a generator element
  652. function atomGenerator(s, generator) {
  653.   generator.QueryInterface(Ci.nsIFeedGenerator);
  654.   generator.agent = trimString(s);
  655.   return generator;
  656. }
  657.  
  658. // post-process atom:logo to create an RSS2-like structure
  659. function atomLogo(s, logo) {
  660.   logo.setPropertyAsAString("url", trimString(s));
  661. }
  662.  
  663. // post-process an RSS category, map it to the Atom fields.
  664. function rssCatTerm(s, cat) {
  665.   // add slash handling?
  666.   cat.setPropertyAsAString("term", trimString(s));
  667.   return cat;
  668.  
  669. // post-process a GUID 
  670. function rssGuid(s, guid) {
  671.   guid.setPropertyAsAString("guid", trimString(s));
  672.   return guid;
  673. }
  674.  
  675. // post-process an RSS author element
  676. //
  677. // It can contain a field like this:
  678. // 
  679. //  <author>lawyer@boyer.net (Lawyer Boyer)</author>
  680. //
  681. // or, delightfully, a field like this:
  682. //
  683. //  <dc:creator>Simon St.Laurent (mailto:simonstl@simonstl.com)</dc:creator>
  684. //
  685. // We want to split this up and assign it to corresponding Atom
  686. // fields.
  687. //
  688. function rssAuthor(s,author) {
  689.   author.QueryInterface(Ci.nsIFeedPerson);
  690.   // check for RSS2 string format
  691.   var chars = trimString(s);
  692.   var matches = chars.match(/(.*)\((.*)\)/);
  693.   var emailCheck = 
  694.     /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  695.   if (matches) {
  696.     var match1 = trimString(matches[1]);
  697.     var match2 = trimString(matches[2]);
  698.     if (match2.indexOf("mailto:") == 0)
  699.       match2 = match2.substring(7);
  700.     if (emailCheck.test(match1)) {
  701.       author.email = match1;
  702.       author.name = match2;
  703.     }
  704.     else if (emailCheck.test(match2)) {
  705.       author.email = match2;
  706.       author.name = match1;
  707.     }
  708.     else {
  709.       // put it back together
  710.       author.name = match1 + " (" + match2 + ")";
  711.     }
  712.   }
  713.   else {
  714.     author.name = chars;
  715.     if (chars.indexOf('@'))
  716.       author.email = chars;
  717.   }
  718.   return author;
  719. }
  720.  
  721. //
  722. // skipHours and skipDays map to arrays, so we need to change the
  723. // string to an nsISupports in order to stick it in there.
  724. //
  725. function rssArrayElement(s) {
  726.   var str = Cc["@mozilla.org/supports-string;1"].
  727.               createInstance(Ci.nsISupportsString);
  728.   str.data = s;
  729.   str.QueryInterface(Ci.nsISupportsString);
  730.   return str;
  731. }
  732.  
  733. /***** Some feed utils from TBird *****/
  734.  
  735. /**
  736.  * Tests a RFC822 date against a regex.
  737.  * @param aDateStr A string to test as an RFC822 date.
  738.  *
  739.  * @returns A boolean indicating whether the string is a valid RFC822 date.
  740.  */
  741. function isValidRFC822Date(aDateStr) {
  742.   var regex = new RegExp(RFC822_RE);
  743.   return regex.test(aDateStr);
  744. }
  745.  
  746. /**
  747.  * Removes leading and trailing whitespace from a string.
  748.  * @param s The string to trim.
  749.  *
  750.  * @returns A new string with whitespace stripped.
  751.  */
  752. function trimString(s) {
  753.   return(s.replace(/^\s+/, "").replace(/\s+$/, ""));
  754. }
  755.  
  756. // Regular expression matching RFC822 dates 
  757. const RFC822_RE = "^(((Mon)|(Tue)|(Wed)|(Thu)|(Fri)|(Sat)|(Sun)), *)?\\d\\d?"
  758. + " +((Jan)|(Feb)|(Mar)|(Apr)|(May)|(Jun)|(Jul)|(Aug)|(Sep)|(Oct)|(Nov)|(Dec))"
  759. + " +\\d\\d(\\d\\d)? +\\d\\d:\\d\\d(:\\d\\d)? +(([+-]?\\d\\d\\d\\d)|(UT)|(GMT)"
  760. + "|(EST)|(EDT)|(CST)|(CDT)|(MST)|(MDT)|(PST)|(PDT)|\\w)$";
  761.  
  762. /**
  763.  * XXX -- need to decide what this should return. 
  764.  * XXX -- Is there a Date class usable from C++?
  765.  *
  766.  * Tries tries parsing various date formats.
  767.  * @param dateString
  768.  *        A string that is supposedly an RFC822 or RFC3339 date.
  769.  * @returns A Date.toString XXX--fixme
  770.  */
  771. function dateParse(dateString) {
  772.   var date = trimString(dateString);
  773.  
  774.   if (date.search(/^\d\d\d\d/) != -1) //Could be a ISO8601/W3C date
  775.     return W3CToIETFDate(dateString);
  776.  
  777.   if (isValidRFC822Date(date))
  778.     return date; 
  779.   
  780.   if (!isNaN(parseInt(date, 10))) { 
  781.     //It's an integer, so maybe it's a timestamp
  782.     var d = new Date(parseInt(date, 10) * 1000);
  783.     var now = new Date();
  784.     var yeardiff = now.getFullYear() - d.getFullYear();
  785.     if ((yeardiff >= 0) && (yeardiff < 3)) {
  786.       // it's quite likely the correct date. 3 years is an arbitrary cutoff,
  787.       // but this is an invalid date format, and there's no way to verify
  788.       // its correctness.
  789.       return d.toString();
  790.     }
  791.   }
  792.   // Can't help.
  793.   return null;
  794.  
  795.  
  796. const XHTML_NS = "http://www.w3.org/1999/xhtml";
  797.  
  798. // The XHTMLHandler handles inline XHTML found in things like atom:summary
  799. function XHTMLHandler(processor, isAtom) {
  800.   this._buf = "";
  801.   this._processor = processor;
  802.   this._depth = 0;
  803.   this._isAtom = isAtom;
  804. }
  805.  
  806. // The fidelity can be improved here, to allow handling of stuff like
  807. // SVG and MathML. XXX
  808. XHTMLHandler.prototype = {
  809.   startDocument: function XH_startDocument() {
  810.   },
  811.   endDocument: function XH_endDocument() {
  812.   },
  813.   startElement: function XH_startElement(uri, localName, qName, attributes) {
  814.     ++this._depth;
  815.  
  816.     // RFC4287 requires XHTML to be wrapped in a div that is *not* part of 
  817.     // the content. This prevents people from screwing up namespaces, but
  818.     // we need to skip it here.
  819.     if (this._isAtom && this._depth == 1 && localName == "div")
  820.       return;
  821.  
  822.     // If it's an XHTML element, record it. Otherwise, it's ignored.
  823.     if (uri == XHTML_NS) {
  824.       this._buf += "<" + localName;
  825.       for (var i=0; i < attributes.length; ++i) {
  826.         // XHTML attributes aren't in a namespace
  827.         if (attributes.getURI(i) == "") { 
  828.           this._buf += (" " + attributes.getLocalName(i) + "='" +
  829.                         xmlEscape(attributes.getValue(i)) + "'");
  830.         }
  831.       }
  832.       this._buf += ">";
  833.     }
  834.   },
  835.   endElement: function XH_endElement(uri, localName, qName) {
  836.     --this._depth;
  837.     
  838.     // We need to skip outer divs in Atom. See comment in startElement.
  839.     if (this._isAtom && this._depth == 0 && localName == "div")
  840.       return;
  841.  
  842.     // When we peek too far, go back to the main processor
  843.     if (this._depth < 0) {
  844.       this._processor.returnFromXHTMLHandler(trimString(this._buf),
  845.                                              uri, localName, qName);
  846.       return;
  847.     }
  848.     // If it's an XHTML element, record it. Otherwise, it's ignored.
  849.     if (uri == XHTML_NS) {
  850.       this._buf += "</" + localName + ">";
  851.     }
  852.   },
  853.   characters: function XH_characters(data) {
  854.     this._buf += xmlEscape(data);
  855.   },
  856.   startPrefixMapping: function XH_startPrefixMapping() {
  857.   },
  858.   endPrefixMapping: function XH_endPrefixMapping() {
  859.   },
  860.   processingInstruction: function XH_processingInstruction() {
  861.   }, 
  862. }
  863.  
  864. /**
  865.  * The ExtensionHandler deals with elements we haven't explicitly
  866.  * added to our transition table in the FeedProcessor.
  867.  */
  868. function ExtensionHandler(processor) {
  869.   this._buf = "";
  870.   this._depth = 0;
  871.   this._hasChildElements = false;
  872.  
  873.   // The FeedProcessor
  874.   this._processor = processor;
  875.  
  876.   // Fields of the outermost extension element.
  877.   this._localName = null;
  878.   this._uri = null;
  879.   this._qName = null;
  880.   this._attrs = null;
  881. }
  882.  
  883. ExtensionHandler.prototype = {
  884.   startDocument: function EH_startDocument() {
  885.   },
  886.   endDocument: function EH_endDocument() {
  887.   },
  888.   startElement: function EH_startElement(uri, localName, qName, attrs) {
  889.     ++this._depth;
  890.     var prefix = gNamespaces[uri] ? gNamespaces[uri] + ":" : "";
  891.     var key =  prefix + localName;
  892.     
  893.     if (this._depth == 1) {
  894.       this._uri = uri;
  895.       this._localName = localName;
  896.       this._qName = qName;
  897.       this._attrs = attrs;
  898.     }
  899.     
  900.     // if we descend into another element, we won't send text
  901.     this._hasChildElements = (this._depth > 1);
  902.     
  903.   },
  904.   endElement: function EH_endElement(uri, localName, qName) {
  905.     --this._depth;
  906.     if (this._depth == 0) {
  907.       var text = this._hasChildElements ? null : trimString(this._buf);
  908.       this._processor.returnFromExtHandler(this._uri, this._localName, 
  909.                                            text, this._attrs);
  910.     }
  911.   },
  912.   characters: function EH_characters(data) {
  913.     if (!this._hasChildElements)
  914.       this._buf += data;
  915.   },
  916.   startPrefixMapping: function EH_startPrefixMapping() {
  917.   },
  918.   endPrefixMapping: function EH_endPrefixMapping() {
  919.   },
  920.   processingInstruction: function EH_processingInstruction() {
  921.   }, 
  922. };
  923.  
  924.  
  925. /**
  926.  * ElementInfo is a simple container object that describes
  927.  * some characteristics of a feed element. For example, it
  928.  * says whether an element can be expected to appear more
  929.  * than once inside a given entry or feed.
  930.  */ 
  931. function ElementInfo(fieldName, containerClass, closeFunc, isArray) {
  932.   this.fieldName = fieldName;
  933.   this.containerClass = containerClass;
  934.   this.closeFunc = closeFunc;
  935.   this.isArray = isArray;
  936.   this.isWrapper = false;
  937. }
  938.  
  939. /**
  940.  * FeedElementInfo represents a feed element, usually the root.
  941.  */
  942. function FeedElementInfo(fieldName, feedVersion) {
  943.   this.isWrapper = false;
  944.   this.fieldName = fieldName;
  945.   this.feedVersion = feedVersion;
  946. }
  947.  
  948. /**
  949.  * Some feed formats include vestigial wrapper elements that we don't
  950.  * want to include in our object model, but we do need to keep track
  951.  * of during parsing.
  952.  */
  953. function WrapperElementInfo(fieldName) {
  954.   this.isWrapper = true;
  955.   this.fieldName = fieldName;
  956. }
  957.  
  958. /***** The Processor *****/
  959. function FeedProcessor() {
  960.   this._reader = Cc[SAX_CONTRACTID].createInstance(Ci.nsISAXXMLReader);
  961.   this._buf =  "";
  962.   this._feed = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
  963.   this._handlerStack = [];
  964.   this._xmlBaseStack = []; // sparse array keyed to nesting depth
  965.   this._depth = 0;
  966.   this._state = "START";
  967.   this._result = null;
  968.   this._extensionHandler = null;
  969.   this._xhtmlHandler = null;
  970.  
  971.   // The nsIFeedResultListener waiting for the parse results
  972.   this.listener = null;
  973.  
  974.   // These elements can contain (X)HTML or plain text.
  975.   // We keep a table here that contains their default treatment
  976.   this._textConstructs = {"atom:title":"text",
  977.                           "atom:summary":"text",
  978.                           "atom:rights":"text",
  979.                           "atom:content":"text",
  980.                           "atom:subtitle":"text",
  981.                           "description":"html",
  982.                           "rss1:description":"html",
  983.                           "dc:description":"html",
  984.                           "content:encoded":"html",
  985.                           "title":"text",
  986.                           "rss1:title":"text",
  987.                           "atom03:title":"text",
  988.                           "atom03:tagline":"text",
  989.                           "atom03:summary":"text",
  990.                           "atom03:content":"text"};
  991.   this._stack = [];
  992.  
  993.   this._trans = {   
  994.     "START": {
  995.       //If we hit a root RSS element, treat as RSS2.
  996.       "rss": new FeedElementInfo("RSS2", "rss2"),
  997.  
  998.       // If we hit an RDF element, if could be RSS1, but we can't
  999.       // verify that until we hit a rss1:channel element.
  1000.       "rdf:RDF": new WrapperElementInfo("RDF"),
  1001.  
  1002.       // If we hit a Atom 1.0 element, treat as Atom 1.0.
  1003.       "atom:feed": new FeedElementInfo("Atom", "atom"),
  1004.  
  1005.       // Treat as Atom 0.3
  1006.       "atom03:feed": new FeedElementInfo("Atom03", "atom03"),
  1007.     },
  1008.     
  1009.     /********* RSS2 **********/
  1010.     "IN_RSS2": {
  1011.       "channel": new WrapperElementInfo("channel")
  1012.     },
  1013.  
  1014.     "IN_CHANNEL": {
  1015.       "item": new ElementInfo("items", Cc[ENTRY_CONTRACTID], null, true),
  1016.       "managingEditor": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1017.                                         rssAuthor, true),
  1018.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1019.                                     rssAuthor, true),
  1020.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1021.                                    rssAuthor, true),
  1022.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1023.                                          rssAuthor, true),
  1024.       "category": new ElementInfo("categories", null, rssCatTerm, true),
  1025.       "cloud": new ElementInfo("cloud", null, null, false),
  1026.       "image": new ElementInfo("image", null, null, false),
  1027.       "textInput": new ElementInfo("textInput", null, null, false),
  1028.       "skipDays": new ElementInfo("skipDays", null, null, false),
  1029.       "skipHours": new ElementInfo("skipHours", null, null, false),
  1030.       "generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1031.                                    atomGenerator, false),
  1032.     },
  1033.  
  1034.     "IN_ITEMS": {
  1035.       "author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1036.                                 rssAuthor, true),
  1037.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1038.                                     rssAuthor, true),
  1039.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1040.                                    rssAuthor, true),
  1041.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1042.                                          rssAuthor, true),
  1043.       "category": new ElementInfo("categories", null, rssCatTerm, true),
  1044.       "enclosure": new ElementInfo("enclosure", null, null, true),
  1045.       "guid": new ElementInfo("guid", null, rssGuid, false)
  1046.     },
  1047.  
  1048.     "IN_SKIPDAYS": {
  1049.       "day": new ElementInfo("days", null, rssArrayElement, true)
  1050.     },
  1051.  
  1052.     "IN_SKIPHOURS":{
  1053.       "hour": new ElementInfo("hours", null, rssArrayElement, true)
  1054.     },
  1055.  
  1056.     /********* RSS1 **********/
  1057.     "IN_RDF": {
  1058.       // If we hit a rss1:channel, we can verify that we have RSS1
  1059.       "rss1:channel": new FeedElementInfo("rdf_channel", "rss1"),
  1060.       "rss1:image": new ElementInfo("image", null, null, false),
  1061.       "rss1:textinput": new ElementInfo("textInput", null, null, false),
  1062.       "rss1:item": new ElementInfo("items", Cc[ENTRY_CONTRACTID], null, true),
  1063.     },
  1064.  
  1065.     "IN_RDF_CHANNEL": {
  1066.       "admin:generatorAgent": new ElementInfo("generator",
  1067.                                               Cc[GENERATOR_CONTRACTID],
  1068.                                               null, false),
  1069.       "dc:creator": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1070.                                     rssAuthor, true),
  1071.       "dc:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1072.                                    rssAuthor, true),
  1073.       "dc:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1074.                                          rssAuthor, true),
  1075.     },
  1076.  
  1077.     /********* ATOM 1.0 **********/
  1078.     "IN_ATOM": {
  1079.       "atom:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1080.                                      null, true),
  1081.       "atom:generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1082.                                         atomGenerator, false),
  1083.       "atom:contributor": new ElementInfo("contributors",  Cc[PERSON_CONTRACTID],
  1084.                                           null, true),
  1085.       "atom:link": new ElementInfo("links", null, null, true),
  1086.       "atom:logo": new ElementInfo("atom:logo", null, atomLogo, false),
  1087.       "atom:entry": new ElementInfo("entries", Cc[ENTRY_CONTRACTID],
  1088.                                     null, true)
  1089.     },
  1090.  
  1091.     "IN_ENTRIES": {
  1092.       "atom:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1093.                                      null, true),
  1094.       "atom:contributor": new ElementInfo("contributors", Cc[PERSON_CONTRACTID],
  1095.                                           null, true),
  1096.       "atom:link": new ElementInfo("links", null, null, true),
  1097.     },
  1098.  
  1099.     /********* ATOM 0.3 **********/
  1100.     "IN_ATOM03": {
  1101.       "atom03:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1102.                                        null, true),
  1103.       "atom03:contributor": new ElementInfo("contributors",
  1104.                                             Cc[PERSON_CONTRACTID],
  1105.                                             null, true),
  1106.       "atom03:link": new ElementInfo("links", null, null, true),
  1107.       "atom03:entry": new ElementInfo("atom03_entries", Cc[ENTRY_CONTRACTID],
  1108.                                       null, true),
  1109.       "atom03:generator": new ElementInfo("generator", Cc[GENERATOR_CONTRACTID],
  1110.                                           atomGenerator, false),
  1111.     },
  1112.  
  1113.     "IN_ATOM03_ENTRIES": {
  1114.       "atom03:author": new ElementInfo("authors", Cc[PERSON_CONTRACTID],
  1115.                                        null, true),
  1116.       "atom03:contributor": new ElementInfo("contributors",
  1117.                                             Cc[PERSON_CONTRACTID],
  1118.                                             null, true),
  1119.       "atom03:link": new ElementInfo("links", null, null, true),
  1120.       "atom03:entry": new ElementInfo("atom03_entries", Cc[ENTRY_CONTRACTID],
  1121.                                       null, true)
  1122.     }
  1123.   }
  1124. }
  1125.  
  1126. // See startElement for a long description of how feeds are processed.
  1127. FeedProcessor.prototype = { 
  1128.   
  1129.   // Set ourselves as the SAX handler, and set the base URI
  1130.   _init: function FP_init(uri) {
  1131.     this._reader.contentHandler = this;
  1132.     this._reader.errorHandler = this;
  1133.     this._result = Cc[FR_CONTRACTID].createInstance(Ci.nsIFeedResult);
  1134.     if (uri) {
  1135.       this._result.uri = uri;
  1136.       this._reader.baseURI = uri;
  1137.       this._xmlBaseStack[0] = uri;
  1138.     }
  1139.   },
  1140.  
  1141.   // This function is called once we figure out what type of feed
  1142.   // we're dealing with. Some feed types require digging a bit further
  1143.   // than the root.
  1144.   _docVerified: function FP_docVerified(version) {
  1145.     this._result.doc = Cc[FEED_CONTRACTID].createInstance(Ci.nsIFeed);
  1146.     this._result.doc.baseURI = 
  1147.       this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1148.     this._result.doc.fields = this._feed;
  1149.     this._result.version = version;
  1150.   },
  1151.  
  1152.   // When we're done with the feed, let the listener know what
  1153.   // happened.
  1154.   _sendResult: function FP_sendResult() {
  1155.     try {
  1156.       // Can be null when a non-feed is fed to us
  1157.       if (this._result.doc)
  1158.         this._result.doc.normalize();
  1159.     }
  1160.     catch (e) {
  1161.       LOG("FIXME: " + e);
  1162.     }
  1163.  
  1164.     try {
  1165.       if (this.listener != null)
  1166.         this.listener.handleResult(this._result);
  1167.     }
  1168.     finally {
  1169.       this._result = null;
  1170.       this._reader = null;
  1171.     }
  1172.   },
  1173.  
  1174.   // Parsing functions
  1175.   parseFromStream: function FP_parseFromStream(stream, uri) {
  1176.     this._init(uri);
  1177.     this._reader.parseFromStream(stream, null, stream.available(), 
  1178.                                  "application/xml");
  1179.     this._reader = null;
  1180.   },
  1181.  
  1182.   parseFromString: function FP_parseFromString(inputString, uri) {
  1183.     this._init(uri);
  1184.     this._reader.parseFromString(inputString, "application/xml");
  1185.     this._reader = null;
  1186.   },
  1187.  
  1188.   parseAsync: function FP_parseAsync(requestObserver, uri) {
  1189.     this._init(uri);
  1190.     this._reader.parseAsync(requestObserver);
  1191.   },
  1192.  
  1193.   // nsIStreamListener 
  1194.  
  1195.   // The XMLReader will throw sensible exceptions if these get called
  1196.   // out of order.
  1197.   onStartRequest: function FP_onStartRequest(request, context) {
  1198.     this._reader.onStartRequest(request, context);
  1199.   },
  1200.  
  1201.   onStopRequest: function FP_onStopRequest(request, context, statusCode) {
  1202.     this._reader.onStopRequest(request, context, statusCode);
  1203.   },
  1204.  
  1205.   onDataAvailable:
  1206.   function FP_onDataAvailable(request, context, inputStream, offset, count) {
  1207.     this._reader.onDataAvailable(request, context, inputStream, offset, count);
  1208.   },
  1209.  
  1210.   // nsISAXErrorHandler
  1211.  
  1212.   // We only care about fatal errors. When this happens, we may have
  1213.   // parsed through the feed metadata and some number of entries. The
  1214.   // listener can still show some of that data if it wants, and we'll
  1215.   // set the bozo bit to indicate we were unable to parse all the way
  1216.   // through.
  1217.   fatalError: function FP_reportError() {
  1218.     this._result.bozo = true;
  1219.     //XXX need to QI to FeedProgressListener
  1220.     this._sendResult();
  1221.   },
  1222.  
  1223.   // nsISAXContentHandler
  1224.  
  1225.   startDocument: function FP_startDocument() {
  1226.     //LOG("----------");
  1227.   },
  1228.  
  1229.   endDocument: function FP_endDocument() {
  1230.     this._sendResult();
  1231.   },
  1232.  
  1233.   // The transitions defined above identify elements that contain more
  1234.   // than just text. For example RSS items contain many fields, and so
  1235.   // do Atom authors. The only commonly used elements that contain
  1236.   // mixed content are Atom Text Constructs of type="xhtml", which we
  1237.   // delegate to another handler for cleaning. That leaves a couple
  1238.   // different types of elements to deal with: those that should occur
  1239.   // only once, such as title elements, and those that can occur
  1240.   // multiple times, such as the RSS category element and the Atom
  1241.   // link element. Most of the RSS1/DC elements can occur multiple
  1242.   // times in theory, but in practice, the only ones that do have
  1243.   // analogues in Atom. 
  1244.   //
  1245.   // Some elements are also groups of attributes or sub-elements,
  1246.   // while others are simple text fields. For the most part, we don't
  1247.   // have to pay explicit attention to the simple text elements,
  1248.   // unless we want to post-process the resulting string to transform
  1249.   // it into some richer object like a Date or URI.
  1250.   //
  1251.   // Elements that have more sophisticated content models still end up
  1252.   // being dictionaries, whether they are based on attributes like RSS
  1253.   // cloud, sub-elements like Atom author, or even items and
  1254.   // entries. These elements are treated as "containers". It's
  1255.   // theoretically possible for a container to have an attribute with 
  1256.   // the same universal name as a sub-element, but none of the feed
  1257.   // formats allow this by default, and I don't of any extension that
  1258.   // works this way.
  1259.   //
  1260.   startElement: function FP_startElement(uri, localName, qName, attributes) {
  1261.     this._buf = "";
  1262.     ++this._depth;
  1263.     var elementInfo;
  1264.  
  1265.     //LOG("<" + localName + ">");
  1266.  
  1267.     // Check for xml:base
  1268.     var base = attributes.getValueFromName(XMLNS, "base");
  1269.     if (base) {
  1270.       this._xmlBaseStack[this._depth] =
  1271.         strToURI(base, this._xmlBaseStack[this._xmlBaseStack.length - 1]);
  1272.     }
  1273.  
  1274.     // To identify the element we're dealing with, we look up the
  1275.     // namespace URI in our gNamespaces dictionary, which will give us
  1276.     // a "canonical" prefix for a namespace URI. For example, this
  1277.     // allows Dublin Core "creator" elements to be consistently mapped
  1278.     // to "dc:creator", for easy field access by consumer code. This
  1279.     // strategy also happens to shorten up our state table.
  1280.     var key =  this._prefixForNS(uri) + localName;
  1281.  
  1282.     // Check to see if we need to hand this off to our XHTML handler.
  1283.     // The elements we're dealing with will look like this:
  1284.     // 
  1285.     // <title type="xhtml">
  1286.     //   <div xmlns="http://www.w3.org/1999/xhtml">
  1287.     //     A title with <b>bold</b> and <i>italics</i>.
  1288.     //   </div>
  1289.     // </title>
  1290.     //
  1291.     // When it returns in returnFromXHTMLHandler, the handler should
  1292.     // give us back a string like this: 
  1293.     // 
  1294.     //    "A title with <b>bold</b> and <i>italics</i>."
  1295.     //
  1296.     // The Atom spec explicitly says the div is not part of the content,
  1297.     // and explicitly allows whitespace collapsing.
  1298.     // 
  1299.     if ((this._result.version == "atom" || this._result.version == "atom03") &&
  1300.         this._textConstructs[key] != null) {
  1301.       var type = attributes.getValueFromName("","type");
  1302.       if (type != null && type.indexOf("xhtml") >= 0) {
  1303.         this._xhtmlHandler = 
  1304.           new XHTMLHandler(this, (this._result.version == "atom"));
  1305.         this._reader.contentHandler = this._xhtmlHandler;
  1306.         return;
  1307.       }
  1308.     }
  1309.  
  1310.     // Check our current state, and see if that state has a defined
  1311.     // transition. For example, this._trans["atom:entry"]["atom:author"]
  1312.     // will have one, and it tells us to add an item to our authors array.
  1313.     if (this._trans[this._state] && this._trans[this._state][key]) {
  1314.       elementInfo = this._trans[this._state][key];
  1315.     }
  1316.     else {
  1317.       // If we don't have a transition, hand off to extension handler
  1318.       this._extensionHandler = new ExtensionHandler(this);
  1319.       this._reader.contentHandler = this._extensionHandler;
  1320.       this._extensionHandler.startElement(uri, localName, qName, attributes);
  1321.       return;
  1322.     }
  1323.       
  1324.     // This distinguishes wrappers like 'channel' from elements
  1325.     // we'd actually like to do something with (which will test true).
  1326.     this._handlerStack[this._depth] = elementInfo; 
  1327.     if (elementInfo.isWrapper) {
  1328.       this._state = "IN_" + elementInfo.fieldName.toUpperCase();
  1329.       this._stack.push([this._feed, this._state]);
  1330.     } 
  1331.     else if (elementInfo.feedVersion) {
  1332.       this._state = "IN_" + elementInfo.fieldName.toUpperCase();
  1333.  
  1334.       // Check for the older RSS2 variants
  1335.       if (elementInfo.feedVersion == "rss2")
  1336.         elementInfo.feedVersion = this._findRSSVersion(attributes);
  1337.       else if (uri == RSS090NS)
  1338.         elementInfo.feedVersion = "rss090";
  1339.  
  1340.       this._docVerified(elementInfo.feedVersion);
  1341.       this._stack.push([this._feed, this._state]);
  1342.       this._mapAttributes(this._feed, attributes);
  1343.     }
  1344.     else {
  1345.       this._state = this._processComplexElement(elementInfo, attributes);
  1346.     }
  1347.   },
  1348.  
  1349.   // In the endElement handler, we decrement the stack and look
  1350.   // for cleanup/transition functions to execute. The second part
  1351.   // of the state transition works as above in startElement, but
  1352.   // the state we're looking for is prefixed with an underscore
  1353.   // to distinguish endElement events from startElement events.
  1354.   endElement:  function FP_endElement(uri, localName, qName) {
  1355.     var elementInfo = this._handlerStack[this._depth];
  1356.     //LOG("</" + localName + ">");
  1357.     if (elementInfo && !elementInfo.isWrapper)
  1358.       this._closeComplexElement(elementInfo);
  1359.   
  1360.     // cut down xml:base context
  1361.     if (this._xmlBaseStack.length == this._depth + 1)
  1362.       this._xmlBaseStack = this._xmlBaseStack.slice(0, this._depth);
  1363.  
  1364.     // our new state is whatever is at the top of the stack now
  1365.     if (this._stack.length > 0)
  1366.       this._state = this._stack[this._stack.length - 1][1];
  1367.     this._handlerStack = this._handlerStack.slice(0, this._depth);
  1368.     --this._depth;
  1369.   },
  1370.  
  1371.   // Buffer up character data. The buffer is cleared with every
  1372.   // opening element.
  1373.   characters: function FP_characters(data) {
  1374.     this._buf += data;
  1375.   },
  1376.  
  1377.   // TODO: It would be nice to check new prefixes here, and if they
  1378.   // don't conflict with the ones we've defined, throw them in a 
  1379.   // dictionary to check.
  1380.   startPrefixMapping: function FP_startPrefixMapping() {
  1381.   },
  1382.   endPrefixMapping: function FP_endPrefixMapping() {
  1383.   },
  1384.   processingInstruction: function FP_processingInstruction(target, data) {
  1385.     if (target == "xml-stylesheet") {
  1386.       var hrefAttribute = data.match(/href=[\"\'](.*?)[\"\']/);
  1387.       if (hrefAttribute && hrefAttribute.length == 2) 
  1388.         this._result.stylesheet = gIoService.newURI(hrefAttribute[1], null,
  1389.                                                     this._result.uri);
  1390.     }
  1391.   },
  1392.  
  1393.   // end of nsISAXContentHandler
  1394.  
  1395.   // Handle our more complicated elements--those that contain
  1396.   // attributes and child elements.
  1397.   _processComplexElement:
  1398.   function FP__processComplexElement(elementInfo, attributes) {
  1399.     var obj, key, prefix;
  1400.  
  1401.     // If the container is an entry/item, it'll need to have its 
  1402.     // more esoteric properties put in the 'fields' property bag.
  1403.     if (elementInfo.containerClass == Cc[ENTRY_CONTRACTID]) {
  1404.       obj = elementInfo.containerClass.createInstance(Ci.nsIFeedEntry);
  1405.       obj.baseURI = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1406.       this._mapAttributes(obj.fields, attributes);
  1407.     }
  1408.     else if (elementInfo.containerClass) {
  1409.       obj = elementInfo.containerClass.createInstance(Ci.nsIFeedElementBase);
  1410.       obj.baseURI = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1411.       obj.attributes = attributes; // just set the SAX attributes
  1412.     }
  1413.     else {
  1414.       obj = Cc[BAG_CONTRACTID].createInstance(Ci.nsIWritablePropertyBag2);
  1415.       this._mapAttributes(obj, attributes);
  1416.     }
  1417.  
  1418.     // We should have a container/propertyBag that's had its
  1419.     // attributes processed. Now we need to attach it to its
  1420.     // container.
  1421.     var newProp;
  1422.  
  1423.     // First we'll see what's on top of the stack.
  1424.     var container = this._stack[this._stack.length - 1][0];
  1425.  
  1426.     // Check to see if it has the property
  1427.     var prop;
  1428.     try {
  1429.       prop = container.getProperty(elementInfo.fieldName);
  1430.     }
  1431.     catch(e) {
  1432.     }
  1433.     
  1434.     if (elementInfo.isArray) {
  1435.       if (!prop) {
  1436.         container.setPropertyAsInterface(elementInfo.fieldName,
  1437.                                          Cc[ARRAY_CONTRACTID].
  1438.                                          createInstance(Ci.nsIMutableArray));
  1439.       }
  1440.  
  1441.       newProp = container.getProperty(elementInfo.fieldName);
  1442.       // XXX This QI should not be necessary, but XPConnect seems to fly
  1443.       // off the handle in the browser, and loses track of the interface
  1444.       // on large files. Bug 335638.
  1445.       newProp.QueryInterface(Ci.nsIMutableArray);
  1446.       newProp.appendElement(obj,false);
  1447.       
  1448.       // If new object is an nsIFeedContainer, we want to deal with
  1449.       // its member nsIPropertyBag instead.
  1450.       if (isIFeedContainer(obj))
  1451.         newProp = obj.fields; 
  1452.  
  1453.     }
  1454.     else {
  1455.       // If it doesn't, set it.
  1456.       if (!prop) {
  1457.         container.setPropertyAsInterface(elementInfo.fieldName,obj);
  1458.       }
  1459.       newProp = container.getProperty(elementInfo.fieldName);
  1460.     }
  1461.     
  1462.     // make our new state name, and push the property onto the stack
  1463.     var newState = "IN_" + elementInfo.fieldName.toUpperCase();
  1464.     this._stack.push([newProp, newState, obj]);
  1465.     return newState;
  1466.   },
  1467.  
  1468.   // Sometimes we need reconcile the element content with the object
  1469.   // model for a given feed. We use helper functions to do the
  1470.   // munging, but we need to identify array types here, so the munging
  1471.   // happens only to the last element of an array.
  1472.   _closeComplexElement: function FP__closeComplexElement(elementInfo) {
  1473.     var stateTuple = this._stack.pop();
  1474.     var container = stateTuple[0];
  1475.     var containerParent = stateTuple[2];
  1476.     var element = null;
  1477.     var isArray = isIArray(container);
  1478.  
  1479.     // If it's an array and we have to post-process,
  1480.     // grab the last element
  1481.     if (isArray)
  1482.       element = container.queryElementAt(container.length - 1, Ci.nsISupports);
  1483.     else
  1484.       element = container;
  1485.  
  1486.     // Run the post-processing function if there is one.
  1487.     if (elementInfo.closeFunc)
  1488.       element = elementInfo.closeFunc(this._buf, element);
  1489.  
  1490.     // If an nsIFeedContainer was on top of the stack,
  1491.     // we need to normalize it
  1492.     if (elementInfo.containerClass == Cc[ENTRY_CONTRACTID])
  1493.       containerParent.normalize();
  1494.  
  1495.     // If it's an array, re-set the last element
  1496.     if (isArray)
  1497.       container.replaceElementAt(element, container.length - 1, false);
  1498.   },
  1499.   
  1500.   _prefixForNS: function FP_prefixForNS(uri) {
  1501.     if (!uri)
  1502.       return "";
  1503.     var prefix = gNamespaces[uri];
  1504.     if (prefix)
  1505.       return prefix + ":";
  1506.     if (uri.toLowerCase().indexOf("http://backend.userland.com") == 0)
  1507.       return "";
  1508.     else
  1509.       return null;
  1510.   },
  1511.  
  1512.   _mapAttributes: function FP__mapAttributes(bag, attributes) {
  1513.     // Cycle through the attributes, and set our properties using the
  1514.     // prefix:localNames we find in our namespace dictionary.
  1515.     for (var i = 0; i < attributes.length; ++i) {
  1516.       var key = this._prefixForNS(attributes.getURI(i)) + attributes.getLocalName(i);
  1517.       var val = attributes.getValue(i);
  1518.       bag.setPropertyAsAString(key, val);
  1519.     }
  1520.   },
  1521.  
  1522.   // Only for RSS2esque formats
  1523.   _findRSSVersion: function FP__findRSSVersion(attributes) {
  1524.     var versionAttr = trimString(attributes.getValueFromName("", "version"));
  1525.     var versions = { "0.91":"rss091",
  1526.                      "0.92":"rss092",
  1527.                      "0.93":"rss093",
  1528.                      "0.94":"rss094" }
  1529.     if (versions[versionAttr])
  1530.       return versions[versionAttr];
  1531.     if (versionAttr.substr(0,2) != "2.")
  1532.       return "rssUnknown";
  1533.     return "rss2";
  1534.   },
  1535.  
  1536.   // unknown element values are returned here. See startElement above
  1537.   // for how this works.
  1538.   returnFromExtHandler:
  1539.   function FP_returnExt(uri, localName, chars, attributes) {
  1540.     --this._depth;
  1541.  
  1542.     // take control of the SAX events
  1543.     this._reader.contentHandler = this;
  1544.     if (localName == null && chars == null)
  1545.       return;
  1546.  
  1547.     // we don't take random elements inside rdf:RDF
  1548.     if (this._state == "IN_RDF")
  1549.       return;
  1550.     
  1551.     // Grab the top of the stack
  1552.     var top = this._stack[this._stack.length - 1];
  1553.     if (!top) 
  1554.       return;
  1555.  
  1556.     var container = top[0];
  1557.     // Grab the last element if it's an array
  1558.     if (isIArray(container)) {
  1559.       var contract = this._handlerStack[this._depth].containerClass;
  1560.       // check if it's something specific, but not an entry
  1561.       if (contract && contract != Cc[ENTRY_CONTRACTID]) {
  1562.         var el = container.queryElementAt(container.length - 1, 
  1563.                                           Ci.nsIFeedElementBase);
  1564.         // XXX there must be a way to flatten these interfaces
  1565.         if (contract == Cc[PERSON_CONTRACTID]) 
  1566.           el.QueryInterface(Ci.nsIFeedPerson);
  1567.         else
  1568.           return; // don't know about this interface
  1569.  
  1570.         var propName = localName;
  1571.         var prefix = gNamespaces[uri];
  1572.  
  1573.         // synonyms
  1574.         if ((uri == "" || 
  1575.              prefix &&
  1576.              ((prefix.indexOf("atom") > -1) ||
  1577.               (prefix.indexOf("rss") > -1))) && 
  1578.             (propName == "url" || propName == "href"))
  1579.           propName = "uri";
  1580.         
  1581.         try {
  1582.           if (el[propName] !== "undefined") {
  1583.             var propValue = chars;
  1584.             // convert URI-bearing values to an nsIURI
  1585.             if (propName == "uri") {
  1586.               var base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1587.               propValue = strToURI(chars, base);
  1588.             }
  1589.             el[propName] = propValue;
  1590.           }
  1591.         }
  1592.         catch(e) {
  1593.           // ignore XPConnect errors
  1594.         }
  1595.         // the rest of the function deals with entry- and feed-level stuff
  1596.         return; 
  1597.       } 
  1598.       else {
  1599.         container = container.queryElementAt(container.length - 1, 
  1600.                                              Ci.nsIWritablePropertyBag2);
  1601.       }
  1602.     }
  1603.     
  1604.     // Make the buffer our new property
  1605.     var propName = this._prefixForNS(uri) + localName;
  1606.  
  1607.     // But, it could be something containing HTML. If so,
  1608.     // we need to know about that.
  1609.     if (this._textConstructs[propName] != null &&
  1610.         this._handlerStack[this._depth].containerClass !== null) {
  1611.       var newProp = Cc[TEXTCONSTRUCT_CONTRACTID].
  1612.                     createInstance(Ci.nsIFeedTextConstruct);
  1613.       newProp.text = chars;
  1614.       // Look up the default type in our table
  1615.       var type = this._textConstructs[propName];
  1616.       var typeAttribute = attributes.getValueFromName("","type");
  1617.       if (this._result.version == "atom" && typeAttribute != null) {
  1618.         type = typeAttribute;
  1619.       }
  1620.       else if (this._result.version == "atom03" && typeAttribute != null) {
  1621.         if (typeAttribute.toLowerCase().indexOf("xhtml") >= 0) {
  1622.           type = "xhtml";
  1623.         }
  1624.         else if (typeAttribute.toLowerCase().indexOf("html") >= 0) {
  1625.           type = "html";
  1626.         }
  1627.         else if (typeAttribute.toLowerCase().indexOf("text") >= 0) {
  1628.           type = "text";
  1629.         }
  1630.       }
  1631.       
  1632.       // If it's rss feed-level description, it's not supposed to have html
  1633.       if (this._result.version.indexOf("rss") >= 0 &&
  1634.           this._handlerStack[this._depth].containerClass != ENTRY_CONTRACTID) {
  1635.         type = "text";
  1636.       }
  1637.  
  1638.       newProp.type = type;
  1639.       newProp.base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1640.       container.setPropertyAsInterface(propName, newProp);
  1641.     }
  1642.     else {
  1643.       container.setPropertyAsAString(propName, chars);
  1644.     }
  1645.     
  1646.   },
  1647.  
  1648.   // Sometimes, we'll hand off SAX handling duties to an XHTMLHandler
  1649.   // (see above) that will scrape out non-XHTML stuff, normalize
  1650.   // namespaces, and remove the wrapper div from Atom 1.0. When the
  1651.   // XHTMLHandler is done, it'll callback here.
  1652.   returnFromXHTMLHandler:
  1653.   function FP_returnFromXHTMLHandler(chars, uri, localName, qName) {
  1654.     // retake control of the SAX content events
  1655.     this._reader.contentHandler = this;
  1656.  
  1657.     // Grab the top of the stack
  1658.     var top = this._stack[this._stack.length - 1];
  1659.     if (!top) 
  1660.       return;
  1661.     var container = top[0];
  1662.  
  1663.     // Assign the property
  1664.     var newProp =  newProp = Cc[TEXTCONSTRUCT_CONTRACTID].
  1665.                    createInstance(Ci.nsIFeedTextConstruct);
  1666.     newProp.text = chars;
  1667.     newProp.type = "xhtml";
  1668.     newProp.base = this._xmlBaseStack[this._xmlBaseStack.length - 1];
  1669.     container.setPropertyAsInterface(this._prefixForNS(uri) + localName,
  1670.                                      newProp);
  1671.     
  1672.     // XHTML will cause us to peek too far. The XHTML handler will
  1673.     // send us an end element to call. RFC4287-valid feeds allow a
  1674.     // more graceful way to handle this. Unfortunately, we can't count
  1675.     // on compliance at this point.
  1676.     this.endElement(uri, localName, qName);
  1677.   },
  1678.  
  1679.   // nsISupports
  1680.   QueryInterface: function FP_QueryInterface(iid) {
  1681.     if (iid.equals(Ci.nsIFeedProcessor) ||
  1682.         iid.equals(Ci.nsISAXContentHandler) ||
  1683.         iid.equals(Ci.nsISAXErrorHandler) ||
  1684.         iid.equals(Ci.nsIStreamListener) ||
  1685.         iid.equals(Ci.nsIRequestObserver) ||
  1686.         iid.equals(Ci.nsISupports))
  1687.       return this;
  1688.  
  1689.     throw Cr.NS_ERROR_NOINTERFACE;
  1690.   },
  1691. }
  1692.  
  1693. const FP_CONTRACTID = "@mozilla.org/feed-processor;1";
  1694. const FP_CLASSID = Components.ID("{26acb1f0-28fc-43bc-867a-a46aabc85dd4}");
  1695. const FP_CLASSNAME = "Feed Processor";
  1696. const FR_CONTRACTID = "@mozilla.org/feed-result;1";
  1697. const FR_CLASSID = Components.ID("{072a5c3d-30c6-4f07-b87f-9f63d51403f2}");
  1698. const FR_CLASSNAME = "Feed Result";
  1699. const FEED_CONTRACTID = "@mozilla.org/feed;1";
  1700. const FEED_CLASSID = Components.ID("{5d0cfa97-69dd-4e5e-ac84-f253162e8f9a}");
  1701. const FEED_CLASSNAME = "Feed";
  1702. const ENTRY_CONTRACTID = "@mozilla.org/feed-entry;1";
  1703. const ENTRY_CLASSID = Components.ID("{8e4444ff-8e99-4bdd-aa7f-fb3c1c77319f}");
  1704. const ENTRY_CLASSNAME = "Feed Entry";
  1705. const TEXTCONSTRUCT_CONTRACTID = "@mozilla.org/feed-textconstruct;1";
  1706. const TEXTCONSTRUCT_CLASSID =
  1707.   Components.ID("{b992ddcd-3899-4320-9909-924b3e72c922}");
  1708. const TEXTCONSTRUCT_CLASSNAME = "Feed Text Construct";
  1709. const GENERATOR_CONTRACTID = "@mozilla.org/feed-generator;1";
  1710. const GENERATOR_CLASSID =
  1711.   Components.ID("{414af362-9ad8-4296-898e-62247f25a20e}");
  1712. const GENERATOR_CLASSNAME = "Feed Generator";
  1713. const PERSON_CONTRACTID = "@mozilla.org/feed-person;1";
  1714. const PERSON_CLASSID = Components.ID("{95c963b7-20b2-11db-92f6-001422106990}");
  1715. const PERSON_CLASSNAME = "Feed Person";
  1716.  
  1717. function GenericComponentFactory(ctor) {
  1718.   this._ctor = ctor;
  1719. }
  1720.  
  1721. GenericComponentFactory.prototype = {
  1722.  
  1723.   _ctor: null,
  1724.  
  1725.   // nsIFactory
  1726.   createInstance: function(outer, iid) {
  1727.     if (outer != null)
  1728.       throw Cr.NS_ERROR_NO_AGGREGATION;
  1729.     return (new this._ctor()).QueryInterface(iid);
  1730.   },
  1731.  
  1732.   // nsISupports
  1733.   QueryInterface: function(iid) {
  1734.     if (iid.equals(Ci.nsIFactory) ||
  1735.         iid.equals(Ci.nsISupports))
  1736.       return this;
  1737.     throw Cr.NS_ERROR_NO_INTERFACE;
  1738.   },
  1739.  
  1740. };
  1741.  
  1742. var Module = {
  1743.   QueryInterface: function(iid) {
  1744.     if (iid.equals(Ci.nsIModule) || 
  1745.         iid.equals(Ci.nsISupports))
  1746.       return this;
  1747.  
  1748.     throw Cr.NS_ERROR_NO_INTERFACE;
  1749.   },
  1750.  
  1751.   getClassObject: function(cm, cid, iid) {
  1752.     if (!iid.equals(Ci.nsIFactory))
  1753.       throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1754.  
  1755.     if (cid.equals(FP_CLASSID))
  1756.       return new GenericComponentFactory(FeedProcessor);
  1757.     if (cid.equals(FR_CLASSID))
  1758.       return new GenericComponentFactory(FeedResult);
  1759.     if (cid.equals(FEED_CLASSID))
  1760.       return new GenericComponentFactory(Feed);
  1761.     if (cid.equals(ENTRY_CLASSID))
  1762.       return new GenericComponentFactory(Entry);
  1763.     if (cid.equals(TEXTCONSTRUCT_CLASSID))
  1764.       return new GenericComponentFactory(TextConstruct);
  1765.     if (cid.equals(GENERATOR_CLASSID))
  1766.       return new GenericComponentFactory(Generator);
  1767.     if (cid.equals(PERSON_CLASSID))
  1768.       return new GenericComponentFactory(Person);
  1769.  
  1770.     throw Cr.NS_ERROR_NO_INTERFACE;
  1771.   },
  1772.  
  1773.   registerSelf: function(cm, file, location, type) {
  1774.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1775.     // Feed Processor
  1776.     cr.registerFactoryLocation(FP_CLASSID, FP_CLASSNAME,
  1777.       FP_CONTRACTID, file, location, type);
  1778.     // Feed Result
  1779.     cr.registerFactoryLocation(FR_CLASSID, FR_CLASSNAME,
  1780.       FR_CONTRACTID, file, location, type);
  1781.     // Feed
  1782.     cr.registerFactoryLocation(FEED_CLASSID, FEED_CLASSNAME,
  1783.       FEED_CONTRACTID, file, location, type);
  1784.     // Entry
  1785.     cr.registerFactoryLocation(ENTRY_CLASSID, ENTRY_CLASSNAME,
  1786.       ENTRY_CONTRACTID, file, location, type);
  1787.     // Text Construct
  1788.     cr.registerFactoryLocation(TEXTCONSTRUCT_CLASSID, TEXTCONSTRUCT_CLASSNAME,
  1789.       TEXTCONSTRUCT_CONTRACTID, file, location, type);
  1790.     // Generator
  1791.     cr.registerFactoryLocation(GENERATOR_CLASSID, GENERATOR_CLASSNAME,
  1792.       GENERATOR_CONTRACTID, file, location, type);
  1793.     // Person
  1794.     cr.registerFactoryLocation(PERSON_CLASSID, PERSON_CLASSNAME,
  1795.       PERSON_CONTRACTID, file, location, type);
  1796.   },
  1797.  
  1798.   unregisterSelf: function(cm, location, type) {
  1799.     var cr = cm.QueryInterface(Ci.nsIComponentRegistrar);
  1800.     // Feed Processor
  1801.     cr.unregisterFactoryLocation(FP_CLASSID, location);
  1802.     // Feed Result
  1803.     cr.unregisterFactoryLocation(FR_CLASSID, location);
  1804.     // Feed
  1805.     cr.unregisterFactoryLocation(FEED_CLASSID, location);
  1806.     // Entry
  1807.     cr.unregisterFactoryLocation(ENTRY_CLASSID, location);
  1808.     // Text Construct
  1809.     cr.unregisterFactoryLocation(TEXTCONSTRUCT_CLASSID, location);
  1810.     // Generator
  1811.     cr.unregisterFactoryLocation(GENERATOR_CLASSID, location);
  1812.     // Person
  1813.     cr.unregisterFactoryLocation(PERSON_CLASSID, location);
  1814.   },
  1815.  
  1816.   canUnload: function(cm) {
  1817.     return true;
  1818.   },
  1819. };
  1820.  
  1821. function NSGetModule(cm, file) {
  1822.   return Module;
  1823. }
  1824.